﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LView.CMS.Core;
using LView.CMS.Core.Extensions;
using LView.CMS.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace LView.CMS.Site.Controllers
{
    public class LMSController : BaseController
    {
        public IActionResult Index()
        {
            return View();
        }

        #region 获取任务信息 + 新增修改任务信息
        [HttpGet]
        public async Task<IActionResult> GetLTasks()
        {
            var (list, total) = await MongodbHelper.Instance.FindListAsync<LTask>();
            return View(total);
        }
        [HttpPost]
        public async Task<IActionResult> SaveLTasks(LTask task)
        {
            if (task.Id.IsNullOrEmpty())
            {
                task.Id = Guid.NewGuid().ToString();
                await MongodbHelper.Instance.InsertOneAsync(task);
            }
            else
            {
                var dbTask = await MongodbHelper.Instance.FindEntityAsync<LTask>(x => x.Id == task.Id);
                if (dbTask.Type == 1)
                    throw new Exception("已发布的不能编辑/Cannot edit published/Không thể xuất bản");

                await MongodbHelper.Instance.UpdateOneAsync(x => x.Id == task.Id, task);
            }
            return Ok();
        }
        #endregion

        #region 获取试卷+新增保存试卷
        [HttpGet]
        public async Task<IActionResult> GetLExams()
        {
            var (list, total) = await MongodbHelper.Instance.FindListAsync<LExam>();
            return View(total);
        }
        [HttpPost]
        public async Task<IActionResult> SaveLTasks(LExam exam)
        {
            if (exam.Id.IsNullOrEmpty())
            {
                exam.Id = Guid.NewGuid().ToString();
                await MongodbHelper.Instance.InsertOneAsync(exam);
            }
            else
            {
                await MongodbHelper.Instance.UpdateOneAsync(x => x.Id == exam.Id, exam);
            }
            return Ok();
        }
        #endregion

        #region 获取进度 + 更新进度
        //课程id，任务id
        [HttpGet]
        public async Task<IActionResult> GetLProcess(LProcess process)
        {
            var retval = await MongodbHelper.Instance.FindEntityAsync<LProcess>(
                x => x.TaskId == process.TaskId &&
                x.CourseId == process.CourseId &&
                x.UserId == CurrentUser.UserId
            );
            return View(retval);
        }
        [HttpGet]
        public async Task<IActionResult> SaveLProcess(LProcess input)
        {
            //分配任务的时候LProcess 就把任务的所有课程insert进去
            var dbProcess = await MongodbHelper.Instance.FindEntityAsync<LProcess>(
                            x => x.TaskId == input.TaskId &&
                            x.CourseId == input.CourseId &&
                            x.UserId == CurrentUser.UserId);

            //同步更新任务的百分比
            var myTask = await MongodbHelper.Instance.FindEntityAsync<LMyTask>(
                         x => x.UserId == CurrentUser.UserId &&
                         x.TaskId == input.TaskId);

            //查看该User有多少课程
            var (list, total) = await MongodbHelper.Instance.FindListAsync<LProcess>(
                        x => x.UserId == CurrentUser.UserId &&
                        x.TaskId == input.TaskId);
            //更新当前课程总的百分比
            if (list.Count(x => x.CourseId != input.CourseId && x.Percent != 100) == 0 && input.Percent == 100)
            {
                myTask.Percent = 100;
                myTask.Status = 1;
            }
            else
            {
                //计算我的任务总的百分比
                var totalPercent = list.Where(x => x.CourseId != input.CourseId).Sum(x => x.Percent) + input.Percent;
                myTask.Percent = totalPercent / list.Count();
            }
            //更新当前课程总的百分比
            await MongodbHelper.Instance.UpdateOneAsync(x => x.UserId == CurrentUser.UserId &&
                        x.TaskId == input.TaskId, myTask);

            dbProcess.Percent = input.Percent;
            await MongodbHelper.Instance.UpdateOneAsync(
            x => x.TaskId == input.TaskId &&
            x.CourseId == input.CourseId &&
            x.UserId == CurrentUser.UserId, dbProcess);
            return Ok();
        }
        #endregion

        #region 获取我的任务
        [HttpGet]
        public async Task<IActionResult> GetMyTasks()
        {
            var retval = new List<LMyTask>();// (await MongodbHelper.Instance.FindListAsync<LMyTask>(x => x.UserId == CurrentUser.UserId)).list;
            retval.Add(new LMyTask
            {
                Name = "新肺炎测试",
                Percent = 10,
                TaskId = "taskid",
                Status = 0,
                AssignUserName = "指派人:张三"
            });
            return View(retval);
            //return Success(retval);
        }
        #endregion

        #region 分配任务
        //传个TaskId,传个用户Id就行了
        public async Task<IActionResult> AssginTask(LProcess input)
        {
            var task = await MongodbHelper.Instance.FindEntityAsync<LTask>(x => x.Id == input.TaskId);
            var lprocess = new List<LProcess>();
            task.Category.ForEach(category =>
            {
                category.Course.ForEach(course =>
                {
                    lprocess.Add(new LProcess
                    {
                        CourseId = course.CourseId,
                        Id = Guid.NewGuid().ToString(),
                        Percent = 0,
                        TaskId = input.TaskId,
                        UserId = input.UserId
                    });
                });
            });
            await MongodbHelper.Instance.InsertManyAsync(lprocess);
            return Ok();
        }
        #endregion
    }
}
